package com.zcy.gift.service.impl;

import com.zcy.gift.client.AuthClient;
import com.zcy.gift.constants.BaseConstants;
import com.zcy.gift.domain.Employee;
import com.zcy.gift.domain.LoginUser;
import com.zcy.gift.domain.Tenant;
import com.zcy.gift.exception.BusinessException;
import com.zcy.gift.exception.ResponseCode;
import com.zcy.gift.exception.RonghuaAssert;
import com.zcy.gift.mapper.EmployeeMapper;
import com.zcy.gift.mapper.TenantMapper;
import com.zcy.gift.mapper.TenantMealMapper;
import com.zcy.gift.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zcy.gift.util.BaiduAuditUtils;
import com.zcy.gift.util.MailUtil;
import com.zcy.gift.util.encrypt.MD5;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zcy
 * @since 2024-01-24
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private TenantMealMapper tenantMealMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private AuthClient authClient;


    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void settlement(Tenant tenant) {
        // 参数校验
        settlementValidate(tenant);
        // 审核 -公司名 -地址 -logo
        List<String> text = Arrays.asList(tenant.getCompanyName(), tenant.getCompanyNum(), tenant.getAddress());
        List<String> img = Arrays.asList(tenant.getLogo());
        Map<String, Object> map = BaiduAuditUtils.censor(text, img);
        Boolean success = (Boolean) map.get("success");
        String message = (String) map.get("message");

        // 保存租户信息
        tenantMapper.insert(tenant);
        // 保存用户信息
        Employee employee = employeeMapper.selectByName(tenant.getAdmin().getUsername());
        if (Objects.nonNull(employee)) {
            // 校验密码是否正确
            if (MD5.validateMD5(BaseConstants.PASSWORD_ENCRYPT_PREFIX + tenant.getAdmin().getPassword(), employee.getPassword())) {
                // 直接绑定租户
                employeeMapper.updateById(employee.setTenantId(tenant.getId()));

            } else {
                throw new BusinessException(ResponseCode.RESPONSE_CODE_40032);
            }
        } else {
            // 用户不存在先保存用户信息
            String salt = UUID.randomUUID().toString();
            String encryptPassword = MD5.getMD5(BaseConstants.PASSWORD_ENCRYPT_PREFIX + employee.getPassword() + salt);
            employee = tenant.getAdmin();

            // 调用鉴权中心保存登录信息
            LoginUser loginUser = new LoginUser()
                    .setUsername(employee.getUsername())
                    .setPassword(encryptPassword)
                    .setTel(employee.getTel())
                    .setEmail(employee.getEmail())
                    .setType(BaseConstants.LoginInfo.TYPE_EMPLOYEE)
                    .setSalt(salt);
            authClient.addOrUpdate(loginUser);

            employeeMapper.insert(employee
                    .setTenantId(tenant.getId())
                    .setPassword(encryptPassword)
                    .setLoginId(loginUser.getId())
                    .setSalt(salt)
                    .setState(BaseConstants.Employee.STATE_DISABLE)
            );

        }

        // 保存租户信息
        tenantMapper.updateById(tenant.setAdminId(employee.getId()));
        // 保存套餐信息
        tenantMealMapper.addBatchByIds(tenant.getMealIdList(), tenant.getId());

        // 审核通过，发送激活邮件
        if (success) {
            redisTemplate.opsForValue().set("active_" + tenant.getId(), tenant);
            mailUtil.sendTenantActiveMail(tenant.getAdmin().getEmail(), tenant.getId());
        } else {
            // 审核未通过，发送未通过原因
            mailUtil.sendTenantFailMail(tenant.getAdmin().getEmail(), message);
        }

    }

    private void settlementValidate(Tenant tenant) {
        // 校验是否选择套餐
        RonghuaAssert.isNotNull(tenant.getMealIdList(), ResponseCode.RESPONSE_CODE_40031);

        // 校验用户密码是否一致
        RonghuaAssert.isEq(tenant.getAdmin().getPassword(), tenant.getAdmin().getConfirmPassword(), ResponseCode.RESPONSE_CODE_40011);
    }


}
